
/**
 * auth:tommy
 * date:2021
 * des:上传图片
 * warn： 该组件只用于多图上传
 * **/
 import store from '@/store'
 const getPolicyBase64 = function () {
  let date = new Date()
  date.setHours(date.getHours() + env.timeout)
  let srcT = date.toISOString()
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
      ["content-length-range", 0, 500 * 1024 * 1024] // 设置上传文件的大小限制,500mb
    ]
  }

  const policyBase64 = base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64) {
  const accesskey = env.AccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
}
const env = require('./config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;

const base64 = require('./base64.js');//Base64,hmac,sha1,crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

// OSS配置
const getOSSconfigData = function (type) {
  let pathStr = 'qqpyyds/mpweixin/user'
  let userIdStr = store.state.userInfo.idCode || store.state.imUserInfo.accountId || "0000000000" // 用户的id作为每个单独的目录
  let typeStr = type || 'other' // 用户的上传类型文件存在单独目录
  let nameStr = new Date().getTime() + Math.floor(Math.random() * 150) // 文件时间戳和随机数生成名字
  let ossFileAddress = pathStr+`/${userIdStr}`+`/${typeStr}`+`/${nameStr}` // 最终用户文件存储的目录、注意拼接不要错了顺序
  let policyBase64 = getPolicyBase64()
  let signature = getSignature(policyBase64) //获取签名
  return {
    //图片名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
    aliyunFileKey: ossFileAddress,
    aliyunServerURL: env.uploadImageUrl, //OSS自定义地址，需要https
    fileHostURL: env.fileHost, //OSS上传地址，需要https
    accessid: env.OSSAccessKeyId,
    policyBase64: policyBase64,
    signature: signature
  }
}


 /**
  * @param {number} number 图片数量 视频固定为1
  * @param {number} maxLength 图片限制最大上传数量
  * @param {number} transmittedLength 已传图片限制最大上传数量
  * @param {string} type 上传类型 image:图片 video:视频
   */
 export function upload (params_ , vm) {
   const OSSconfigData = getOSSconfigData(params_.type)
   let params={ type: 'image', number: 1}
   if(params_){
     params={
       ...params,
       ...params_
     }
   }
   const _this = vm
   return new Promise(async (resolve, reject) => {
     let fnName = 'chooseImage'
     let chooseOptions = {}
     switch (params.type) {
       case 'image':
         fnName = 'chooseImage'
         chooseOptions = {
           count: params.number || 1,
           sizeType: ['original', 'compressed'],
           sourceType: ['album']
         }
         break
      //  case 'video':
      //    fnName = 'chooseMedia'
      //    chooseOptions = {
      //     count: params.number || 1,
      //     mediaType: ['video'],
      //     sourceType: ['album','camera']
      //    }
      //    break
        case 'video':
        fnName = 'chooseVideo'
        chooseOptions = {
          sourceType: ['album'],
          compressed: false,
        }
        break
       default:
         fnName = 'chooseImage'
         chooseOptions = {
           count:  params.number||1,
           sizeType: ['original', 'compressed'],
           sourceType: ['album']
         }
     }
     wx[fnName]({
       ...chooseOptions,
       async success (chooseResponse) {
         console.log(chooseResponse,'chooseResponsechooseResponse')
         if (params.type === 'image') {
           const images = chooseResponse.tempFiles
             for (let i = images.length - 1; i >= 0; i--) {
               if (images[i].size > (1048576*5)) {
                 return resolve({
                   status: 'limit',
                   msg: `图片大小不能超过5M`
                 })
               }
             }
           if (chooseResponse.tempFiles.length > params.number) {
             return resolve({
               status: 'limit',
               msg: `图片张数不能超过${params.number}张`
             })
           }
           if (params.maxLength>0&&(params.transmittedLength+chooseResponse.tempFiles.length>params.maxLength)) {
             return resolve({
               status: 'limit',
               msg: `图片上传总数不能超过${params.maxLength}张`
             })
           }
         }else{
            const video = chooseResponse
            if (video.duration > (60*2)) {
              return resolve({
                status: 'limit',
                msg: `视频时长不可超过2分钟`
              })
            } 
            if (video.size > (1048576*200)) {
              return resolve({
                status: 'limit',
                msg: `视频大小不可超过200M限制`
              })
            }
         }
         let tempFilePath = chooseResponse.tempFiles // 文件路径
         switch (params.type) {
           case 'image':
             tempFilePath = chooseResponse.tempFilePaths
             break
           case 'video':
             tempFilePath = chooseResponse
             break
         }
         const uploadFns = []
         let time = new Date().getTime()
         wx.showLoading({
           title: '上传中',
           mask: true
         })
         if(params.type==='image'){//图片
           for (let i in tempFilePath) {
             time = new Date().getTime() // 以时间戳命名
             uploadFns[i]= await compressImg(tempFilePath[i],375,_this)
           }
           Promise.all(uploadFns).then(result => {
             resolve({
               status: 'success',
               data: result
             })
             wx.hideLoading()
           }).catch(e => {
             reject(e)
             wx.hideLoading()
           })
         }else{//视频
          let fileFormat = tempFilePath.tempFilePath.substring(tempFilePath.tempFilePath.lastIndexOf('.'), tempFilePath.tempFilePath.length) // 获取文件后缀
          // let posterFormat = tempFilePath[0].thumbTempFilePath?tempFilePath[0].thumbTempFilePath.substring(tempFilePath[0].thumbTempFilePath.lastIndexOf('.'), tempFilePath[0].thumbTempFilePath.length): '' // 获取文件后缀
          let poster=''
           resolve(new Promise((resolve, reject) => {
            // if (posterFormat) {
            //   uni.uploadFile({//封面
            //     url: OSSconfigData.fileHostURL,
            //     filePath: tempFilePath[0].thumbTempFilePath,
            //     formData: {
            //       'key': OSSconfigData.aliyunFileKey+posterFormat,
            //       'policy': OSSconfigData.policyBase64,
            //       'OSSAccessKeyId': OSSconfigData.accessid,
            //       'signature': OSSconfigData.signature,
            //       'success_action_status': '200',
            //       'name': time  + posterFormat, // 加i防止同名
            //     },
            //     name: 'file',
            //     async success (uploadResponse) {
            //       if (uploadResponse.statusCode === 200) {
            //         poster = OSSconfigData.fileHostURL + OSSconfigData.aliyunFileKey + posterFormat
            //       }
            //     },
            //     fail (e) {
            //     }
            //   })
            // }
            uni.uploadFile({
              url: OSSconfigData.fileHostURL,//开发者服务器 url
              filePath: tempFilePath.tempFilePath,//要上传文件资源的路径
              name: 'file',//必须填file
              formData: {
                'key': OSSconfigData.aliyunFileKey+fileFormat,
                'policy': OSSconfigData.policyBase64,
                'OSSAccessKeyId': OSSconfigData.accessid,
                'signature': OSSconfigData.signature,
                'success_action_status': '200',
              },
              success: function (res) {
                if (res.statusCode != 200) {
                  console.log("上传错误");
                  return;
                }
                wx.downloadFile({
                  url: OSSconfigData.fileHostURL + OSSconfigData.aliyunFileKey + fileFormat + '?x-oss-process=video/snapshot,t_1000,f_jpg,m_fast',
                  success: function(res) {
                    console.log(res,'resresresresresresresresres视频封面')
                    let posterFormat = res.tempFilePath?res.tempFilePath.substring(res.tempFilePath.lastIndexOf('.'), res.tempFilePath.length): '' // 获取文件后缀
                    uni.uploadFile({//封面
                      url: OSSconfigData.fileHostURL,
                      filePath: res.tempFilePath,
                      formData: {
                        'key': OSSconfigData.aliyunFileKey+posterFormat,
                        'policy': OSSconfigData.policyBase64,
                        'OSSAccessKeyId': OSSconfigData.accessid,
                        'signature': OSSconfigData.signature,
                        'success_action_status': '200',
                        'name': time  + posterFormat, // 加i防止同名
                      },
                      name: 'file',
                      async success (uploadResponse) {
                        if (uploadResponse.statusCode === 200) {
                          poster = OSSconfigData.fileHostURL + OSSconfigData.aliyunFileKey + posterFormat
                          let result ={
                            status: 'success',
                            data: {
                              videoId: new Date().getTime(),
                              wide: tempFilePath.width,
                              high: tempFilePath.height,
                              size: tempFilePath.size,
                              duration: Math.round(tempFilePath.duration),
                              url: OSSconfigData.fileHostURL + OSSconfigData.aliyunFileKey + fileFormat,
                              // thumbnail: OSSconfigData.fileHostURL + OSSconfigData.aliyunFileKey + fileFormat + '?x-oss-process=video/snapshot,t_1000,f_jpg,m_fast'
                              thumbnail: poster,
                            }
                          }
                          resolve(result)
                          wx.hideLoading()
                        }
                      },
                      fail (e) {
                      }
                    })
                  }
                })
              },
              fail: function (err) {
                reject(OSSconfigData.aliyunServerURL)
                wx.hideLoading()
                console.log(err)
              },
            })
           }))
         }
       },
       fail(e){
        reject('用户取消选择')
       }
     })
   })
 }
 export async function compressImg(tempFilePath, limitNum = 375,vm) {
  const OSSconfigData = getOSSconfigData()
  wx.showLoading({
    title: '上传中',
    mask: true
  })
   let that = vm
   return new Promise((resolve, reject) => {
     wx.getImageInfo({
       src: tempFilePath,
       success(res) {
         let imgMsgRes = res
         const fileType='.'+ res.type
        //  if(fileType=='.gif'){
        //    resolve({
        //      checkStatusPass:false,
        //      img_id:new Date().getTime(),
        //      err_type: 'gif'
        //    })
        //    return
        //  }
         var canvasWidth = res.width //图片原始长宽
         var canvasHeight = res.height
         if ((canvasWidth / canvasHeight) < 0.56) { // 说明 要依高为缩放比例--0.56是 750/1334的结果
           if (canvasHeight > 1334) {
             canvasHeight = 1334
             canvasWidth = canvasHeight/res.height*res.width
           }
         } else { // 要依宽为缩放比例
           if (canvasWidth > 750) {
             canvasWidth = 750
             canvasHeight = canvasWidth/res.width*res.height
           }
         }
         let time = +new Date()
         const key = time.toString().substring(time.length-5,time.length)
         resolve(new Promise((resolve, reject) => {
            uni.uploadFile({
              url: OSSconfigData.fileHostURL,//开发者服务器 url
              filePath: tempFilePath,//要上传文件资源的路径
              name: 'file',//必须填file
              formData: {
                'key': OSSconfigData.aliyunFileKey + key +fileType,
                'policy': OSSconfigData.policyBase64,
                'OSSAccessKeyId': OSSconfigData.accessid,
                'signature': OSSconfigData.signature,
                'success_action_status': '200',
              },
              success: function (res) {
                let imgData = {
                  url: OSSconfigData.aliyunServerURL+OSSconfigData.aliyunFileKey + key + fileType,
                  high: imgMsgRes.height,
                  wide: imgMsgRes.width,
                  duration: 5,
                  size: 0,
                  thumbnail: OSSconfigData.aliyunServerURL+OSSconfigData.aliyunFileKey + key + fileType,
                }
                if (res.statusCode != 200) {
                  console.log("上传错误");
                  return;
                }else{
                  console.log(imgData,'上传成功');
                }
                resolve(imgData)
              },
              fail: function (err) {
                reject(OSSconfigData.aliyunServerURL)
                console.log(err)
              },
            })
         }))
       },
       fail: function (res) {
          wx.hideLoading()
         console.log(res.errMsg)
       },
     })
   })
 }
